﻿using System;
using System.Collections.Generic;
using System.Text;
using Emgu.CV;
using Emgu.CV.Structure;
using NIPO.Data;
using NIPO.Plugins;

namespace NIPOCvPlugins.BGSubtractPlugin
{
    public class SimpleBGSubstract : ProcessingPlugin
    {
        private Image<Bgr, float> _background;

        #region Overrides of Plugin

        protected override void Initialize()
        {

        }

        public override void Dispose()
        {
        }

        public override bool IsConfigured
        {
            get { return true; }
        }

        #endregion

        #region Overrides of IPOPlugin

        public override void Reset()
        {
            _background = null;
        }

        #endregion

        #region Overrides of ProcessingPlugin

        public override void ProcessData(object sender, NIPOEventArgs e)
        {
            Image<Bgr, float> image = (e.Data as GenericDTO<Image<Bgr, byte>>).Value.ConvertScale<float>(1,0);

            if (_background == null)
            {
                Log.WriteDebug("No background set, taking current image");
                _background = image;
            }
            _background.RunningAvg(image, 0.01);
            Image<Bgr, float> intermediate = image.AbsDiff(_background);
            //int[] nonzero = intermediate.CountNonzero();
            //Log.WriteDebugFormat("Amount of motion in intermediate: {0}-{1}-{2}", nonzero[0], nonzero[1], nonzero[2]);
            Image<Gray, byte> result = intermediate.Convert<Gray, byte>();//.ThresholdToZero(new Gray(70));
            //Log.WriteDebugFormat("Amount of motion in result: {0}", result.CountNonzero()[0]);
            RaiseNewData(new GenericDTO<Image<Gray, byte>>(result, "EMGU/Image<Gray, byte>", result.Bytes.Length,
                                                           DateTime.Now));
        }

        #endregion
    }
}
